package com.chaochis.wind.base_config.redis_config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.DefaultBaseTypeLimitingValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * redis 配置
 */
@Configuration
public class RedisConfig {

  @Bean(name = "redisTemplate")
  public RedisTemplate<String, Object> redisJackJsonTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> redisJackJsonTemplate = new RedisTemplate<>();
    redisJackJsonTemplate.setConnectionFactory(redisConnectionFactory);

    // 自定义的string序列化器和jackonjson序列化器
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    // 解决jackson2无法反序列化LocalDateTime的问题
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);

    // jackson 序列化器
    var jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    jsonRedisSerializer.setObjectMapper(objectMapper);

    // kv 序列化
    redisJackJsonTemplate.setKeySerializer(stringRedisSerializer);
    redisJackJsonTemplate.setValueSerializer(jsonRedisSerializer);

    // hash 序列化
    redisJackJsonTemplate.setHashKeySerializer(stringRedisSerializer);
    redisJackJsonTemplate.setHashValueSerializer(jsonRedisSerializer);

    redisJackJsonTemplate.afterPropertiesSet();
    return redisJackJsonTemplate;
  }
}
